#include "stitlebar.h"
#include <QPushButton>
#include <QHBoxLayout>
#include <QDateTime>
#include <QDebug>

STitleBar::STitleBar(QWidget *parent)
    : QWidget{parent}
{
    setupUI();
    applyStyles();
    timer = new QTimer(this);
    timer->setInterval(1000);
    timer->start();
    setupConnections();
}


void STitleBar::setupUI(){
    setFixedHeight(32);
    title = new QLabel("");

    datetime = new QLabel();
    SetDateTime();

    closeButton = new QPushButton("×");
    closeButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding);
    closeButton->setFixedWidth(60);



    QHBoxLayout* mainLayout = new QHBoxLayout;
    mainLayout->setAlignment(Qt::AlignVCenter);
    mainLayout->setContentsMargins(12, 6, 12, 6);

    mainLayout->addWidget(title);
    mainLayout->addStretch();
    mainLayout->addWidget(datetime);
    mainLayout->addWidget(closeButton);
    setLayout(mainLayout);
}

void STitleBar::setupConnections(){
    connect(closeButton, &QPushButton::clicked, this, [=]{
        emit closeWindow();
    });

    connect(timer, &QTimer::timeout, this, [=]{
        // qDebug() << "timer...";
        SetDateTime();
    });
};

void STitleBar::applyStyles(){
    title->setStyleSheet(R"(font: bold)");
    setObjectName("styleContainer");
    setAttribute(Qt::WA_StyledBackground);
    setContentsMargins(0, 0, 0, 0);
    setStyleSheet(
        R"(#styleContainer{
            background: #e0e0ff;
            border: 2px solid #409EFF;
            border-radius: 5px;
            padding: 2px;
        }
        )"
        );

};

void STitleBar::SetTitle(QString text) {
    title->setText(text);
}

void STitleBar::SetDateTime(){
    QDateTime now = QDateTime::currentDateTime();
    datetime->setText(now.toString(tr("yyyy年MM月dd日 dddd HH:mm:ss")));
}

void STitleBar::mousePressEvent(QMouseEvent* e) {
    if (e->button() == Qt::LeftButton) {
        m_bDrag = true;
        m_dragStartPos = e->globalPos();
    }
}

void STitleBar::mouseMoveEvent(QMouseEvent* e) {
    if (m_bDrag) {
        QPoint delta = e->globalPos() - m_dragStartPos;
        window()->move(window()->pos() + delta);
        m_dragStartPos = e->globalPos();
    }
}

void STitleBar::mouseReleaseEvent(QMouseEvent* e) {
    Q_UNUSED(e);
    m_bDrag = false;
}
